#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <error.h>
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <signal.h>
#include "head.h"
char file[][MAX_INI_RECORD_NUM];
unsigned int sendnumber = 0;
char server_ip[16];
int server_port;
char mailfrom[100];
void *send_mail(void *args)
{
    FILE *fp;
    char *filename = (char *)args;
    char emailaddr[100];
    int emaillen;
    struct sockaddr_in servaddr;
    int sockfd;
    char recvstr[100];
    char sts_num[4];

    printf("open file:%s\n", filename);
    if ((fp = fopen(filename, "r")) == NULL)
    {
        perror("file open error");
        pthread_exit((void *)1);
    }
    while ((fgets(emailaddr, 100, fp)) != NULL)
    {
        emaillen = strlen(emailaddr);
        emailaddr[emaillen - 1] = '\0';
        sockfd = socket(AF_INET, SOCK_STREAM, 0);
        bzero(&servaddr, sizeof(servaddr));
        servaddr.sin_family = AF_INET;
        inet_pton(AF_INET, server_ip, &servaddr.sin_addr);
        servaddr.sin_port = htons(server_port);
        if(connect(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1)
        {
            perror("connect error");
        }
        recv(sockfd, recvstr, 100, 0);

        // HELO
        char *helo = "HELO\r\n";
        send(sockfd, helo, strlen(helo), 0);
        recv(sockfd, recvstr, 100, 0);
        strncpy(sts_num, recvstr, 3);
        sts_num[3] = '\0';
        char *sts = "250";
        if (strcmp(sts_num, sts) != 0)
        {
            close(sockfd);
            continue;
        }

        // MAIL FROM
        char *mf_str = "MAIL FROM:<machao@corp.the9.com>\r\n";
        send(sockfd, mf_str, strlen(mf_str), 0);
        recv(sockfd, recvstr, 100, 0);

        // RECPT TO
        char rt_str[100];
        char *rt_str_p = "RCPT TO:<";
        char *rt_str_e = ">\r\n";
        strcat(rt_str, rt_str_p);
        strcat(rt_str, emailaddr);
        strcat(rt_str, rt_str_e);
        send(sockfd, rt_str, strlen(rt_str), 0);
        recv(sockfd, recvstr, 100, 0);

        // DATA
        char *data = "DATA\r\nsubject:hello\r\n\r\nhello11\r\n.\r\n";
        send(sockfd, data, strlen(data), 0);
        recv(sockfd, recvstr, 100, 0);

        printf("send mail:%s\n", emailaddr);
        close(sockfd);
    }

    fclose(fp);
    return NULL;
}

void processSignal(int signo)
{
    printf("signal is %d\n", signo);
}

int main(void)
{
    int arraynumber;
    int p_c_num;
    signal(SIGPIPE, processSignal);

    arraynumber = getini();
    pthread_t tid[arraynumber - 1];
    int i;
    for (i = 0; i < arraynumber; i++)
    {
        file[i][strlen(file[i]) - 1] = '\0';
        p_c_num = pthread_create(&tid[i], NULL, send_mail, &file[i]);
        if (p_c_num != 0)
        {
            perror("pthread_create error");
            exit(1);
        }
        pthread_join(tid[i], NULL);
    }
    
    return 0;
}
